package com.example.testwebsocket.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author jie
 * @date 2020/8/11 -9:36
 */
@ServerEndpoint(value = "/websocket/{username}")
@Component
public class WebSocketServer {
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    private static final ConcurrentHashMap<String, WebSocketServer> map = new ConcurrentHashMap<>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        this.session = session;
        map.put(username,this);
        addOnlineCount();           //在线数加1
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("username") String username) {
        map.remove(username);
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message) {
        System.out.println("来自客户端的消息:" + message);
        JSONObject jsonObject = JSON.parseObject(message);

        for(Map.Entry<String, WebSocketServer> entry : map.entrySet()) {
            System.out.println(entry.getKey());
            WebSocketServer item = entry.getValue();
            try {
                if (null != item) {
                    // 如果传递的参数中包含to，则点对点发送
                    String to = jsonObject.getString("toopenid");
                    if (StringUtils.hasLength(to) && to.equals(entry.getKey())) {
                        System.out.println("点对点");
                        item.sendMessage(message);
                        break;
                    }

                    if (!StringUtils.hasLength(to)) {
                        System.out.println("群发");
                        item.sendMessage(message);
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }


    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
